package com.bookstore.servlet.admin;

import com.bookstore.entity.Product;
import com.bookstore.service.ProductService;
import com.bookstore.service.impl.ProductServiceImpl;
import com.bookstore.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/product.do")
public class ProductServlet extends BaseServlet {
    ProductService productService = new ProductServiceImpl();

    public void queryAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Product> products = productService.queryAll();
        request.setAttribute("products", products);
        //通过请求转发 将请求对象转发到商品列表 JSP 上
        request.getRequestDispatcher("/admin/product_list.jsp").forward(request, response);
    }

    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //前端传一个 ID
        String idStr = request.getParameter("id");
        Long id = Long.valueOf(idStr);
        int result = productService.delete(id);
        response.sendRedirect("./product.do?action=queryAll");
    }

    public void insert(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Product product = getParameters(request);
        int result = productService.insert(product);
        response.sendRedirect("./product.do?action=queryAll");
    }

    public void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long id = Long.valueOf(request.getParameter("id"));
        Product product = getParameters(request);
        product.setId(id);
        int result = productService.update(product);
        response.sendRedirect("./product.do?action=queryAll");
    }

    private Product getParameters(HttpServletRequest request) {
        String name = request.getParameter("name");
        Double price = Double.valueOf(request.getParameter("price"));
        String category = request.getParameter("category");
        Integer pNum = Integer.valueOf(request.getParameter("pNum"));
        String imgUrl = request.getParameter("imgUrl");
        String description = request.getParameter("description");
        Product product = new Product(null, name, price, category, pNum, imgUrl, description);
        return product;
    }
}
